package com.cskaoyan.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.api.UserService;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.*;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 登陆接口
 * 验证登录
 * @author beiji
 * @since 2022/05/19 11:34
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController implements UserService {

    @Autowired
    private IKaptchaService iKaptchaService;

    @Autowired
    IUserService userService;

    /**
     * 用户注册功能
     * @author beiji
     * @since 2022/05/20 14:25
     */
    @PostMapping("register")
    public ResponseData register(@RequestBody Map<String,String> map, HttpServletRequest servletRequest){
        UserRegisterRequest request = new UserRegisterRequest();
        request.setUserName(map.get("userName"));
        request.setUserPwd(map.get("userPwd"));
        request.setEmail(map.get("email"));
        String captcha = map.get("captcha");
        // 验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(servletRequest, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse kaptchaCodeResponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        // 验证码不一致
        if(!kaptchaCodeResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }
        UserRegisterResponse response = userService.register(request);
        if(response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**
     * 用户登录功能
     * @author beiji
     * @since 2022/05/20 11:08
     */
    @PostMapping("/login")
    public ResponseData login(@RequestBody Map<String,String> map, HttpServletRequest servletRequest, HttpServletResponse servletResponse){
        UserLoginRequest request = new UserLoginRequest();
        request.setUserName(map.get("userName"));
        request.setPassword(map.get("userPwd"));
        String captcha = map.get("captcha");
        // 验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(servletRequest, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse kaptchaCodeResponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        // 验证码不一致
        if(!kaptchaCodeResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }
        UserLoginResponse response = userService.userLogin(request);
        if (response.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            // 验证成功时在cookie中设置token
            Cookie cookie = CookieUtil.genCookie("access_token", response.getToken(), "/", 7 * 24 * 60 * 60);
            cookie.setHttpOnly(true);
            servletResponse.addCookie(cookie);
            ResponseData responseData = new ResponseUtil().setData(response.getMsg());
            responseData.setResult(response);
            return responseData;
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * 验证登陆
     * @author beiji
     * @since 2022/05/20 11:14
     */
    @GetMapping("/login")
    public ResponseData verifyLogin(HttpServletRequest servletRequest){
        String userInfo = servletRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());
        UserLoginDto userLoginDto = new UserLoginDto();
        userLoginDto.setUid(uid);
        return new ResponseUtil().setData(userLoginDto);
    }

    /**
     * 退出登录
     * @author beiji
     * @since 2022/05/20 11:15
     */
    @GetMapping("/loginOut")
    public ResponseData loginOut(HttpServletRequest servletRequest,HttpServletResponse servletResponse){
        // 退出登录时，清空cookie里的access_token
        Cookie cookie = CookieUtil.genCookie("access_token", null, "/",0);
        servletResponse.addCookie(cookie);
        return new ResponseUtil().setData(null);

    }


    @Override
    @GetMapping("/get/username")
    public String getUsername(Long userId) {

        String username = userService.getUsernameByUserId(userId);
        return username;
    }
}
